package com.huitong.gateway.config;

import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.huitong.gateway.properties.WhiteListProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static org.springframework.http.HttpStatus.UNAUTHORIZED;

/**
 * 网关配置
 *
 * @author fromdrowning
 * @date 2024/4/10 22:14
 */
@Configuration
public class GatewayConfiguration {

    /**
     * Sa-Token全局过滤器配置 进行鉴权操作
     *
     * @param whiteListProperties 放行白名单配置
     * @return Sa-Token全局过滤器
     */
    @Bean
    public SaReactorFilter saReactorFilterCustomizer(WhiteListProperties whiteListProperties) {
        return new SaReactorFilter()
            .addInclude("/**")
            .addExclude("/favicon.ico")
            .setAuth(obj -> {
                // 登录校验
                SaRouter.match("/**")
                    .notMatch(whiteListProperties.getWhites())
                    .check(r -> StpUtil.checkLogin());
            })
            .setError(e -> SaResult.error(e.getMessage())
                .setCode(UNAUTHORIZED.value()));
    }
}
